<?php
/**
 * Created by PhpStorm.
 * User: zhu
 * Date: 2016/10/15
 * Time: 16:30
 */


namespace Forxx\Api;


use Forxx\CacheKeys;
use Forxx\RedisCache;

class Captcha {

    CONST MAX_USED_TIMES = 12;

    CONST CAPTCHA_COOKIE_KEY = 'captcha_sign';

    public $_captchaLib = null;

    private function __construct()
    {
        $this->init();
        $this->_captchaLib = new \CaptchaLib();
    }

    protected function init()
    {
        include_once(L_FRAMEWORK_PATH.'ext/captcha/CaptchaLib.php');
    }

    /**
     * @param $hash
     * @param bool $isReflush
     * @return \CaptchaLib
     */
    public static function getImageHandle($hash,$isReflush = false)
    {
        $captcha = new static();
        $cacheKey = self::getKey($hash);
        $code = '';
        $used = 1;
        if(!$isReflush)
        {
            $cache = RedisCache::instance()->get($cacheKey);
            if(isset($cache['code']) && isset($cache['used']) && $cache['used'] <= self::MAX_USED_TIMES)
            {
                $code = $cache['code'];
                $used = $cache['used'] + 1;
            }
        }
        if(empty($code))
        {
            $code = self::getRandomCode();
        }
        $captcha->_captchaLib->setCode($code);
        self::setCode($hash,$code,$used);
        return $captcha->_captchaLib;
    }

    /**
     * @param string $hash
     * @param string $code
     * @param int $used
     */
    public static function setCode($hash = '',$code = '',$used = 1)
    {
        $cacheKey = self::getKey($hash);
        RedisCache::instance()->setJSON($cacheKey,['code'=>$code,'used'=>intval($used)]);
    }

    /**
     * @param $hash
     * @param $code
     * @return bool
     */
    public static function check($hash ,$code)
    {
        $cacheKey = self::getKey($hash);
        $cache = RedisCache::instance()->getJSON($cacheKey);
        self::setCode($hash);
        if(isset($cache['code']))
        {
            return strtoupper($cache['code']) === strtoupper($code);
        }
        return false;
    }

    public static function getKey($hash)
    {
        return CacheKeys::PRE_CAPTCHA_SIGN.md5(L_APP_PATH.$hash);
    }

    public static function getRandomCode()
    {
        $charsets = 'abcdefghkmnprstuvwxyzABCDEFGHKMNPRSTUVWXYZ23456789';
        return substr(str_shuffle($charsets),0,4);
    }
}